from flask import Flask, render_template
from app.config import config
from app.extensions import db, migrate, socketio



def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])  # 加载配置

    # 初始化扩展（绑定app）
    db.init_app(app)
    migrate.init_app(app, db)
    socketio.init_app(app)

    # 在扩展初始化之后再导入并注册蓝图（避免循环导入）
    from app.routes.auth import auth_bp
    from app.routes.main import main_bp
    from app.routes.api import api_bp
    from app.routes.couple_api import couple_bp
    from app.routes.sql_manager import sqlmanager_bp
    from app.routes.video_player import video_player_bp
    from app.routes.love_list import love_list_bp
    from app.routes.photo import photo_bp

    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)
    app.register_blueprint(api_bp)
    app.register_blueprint(couple_bp)
    app.register_blueprint(sqlmanager_bp)
    app.register_blueprint(video_player_bp)
    app.register_blueprint(love_list_bp)
    app.register_blueprint(photo_bp)


    # 注册错误处理
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('/error/404.html'), 404

    return app
